package com.coocaa.typhoon.api.config.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.nio.file.Files;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2025/10/20 11:17
 * @description
 */
@Configuration
public class ShardingSphereConfig {
    @Value("${tenant.datasource.url}")
    private String url;

    @Value("${tenant.datasource.username}")
    private String username;

    @Value("${tenant.datasource.password}")
    private String password;

    @Bean
    public DataSource dataSource() throws Exception {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName("com.mysql.jdbc.Driver");

        Map<String, DataSource> dataSourceMap = Map.of("ds0", ds);
        ClassPathResource resource = new ClassPathResource("sharding.yaml");
        byte[] yamlBytes = resource.getInputStream().readAllBytes();
        // 加载 ShardingSphere 配置
        return YamlShardingSphereDataSourceFactory.createDataSource(dataSourceMap, yamlBytes);
    }
}
